package edu.pku.se.chocolate.UI.Adapter;

import java.util.ArrayList;

import android.R;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import edu.pku.se.chocolate.ChocolateActivity;
import edu.pku.se.chocolate.datastructure.Message;
import edu.pku.se.chocolate.datastructure.Tag;

public class InformationListAdapter extends BaseExpandableListAdapter{
	
	private Context mContext;
	private ArrayList<Message> ms;
	private Tag tag;
	private final int childSize = 1;
	private Handler myHandler;
	private Handler moreHandler;
	private boolean isFlush = false;
	private boolean isMore = false;
	private int screenWidth = ChocolateActivity.DM.widthPixels;
	public InformationListAdapter(Context mc, Tag tag, Handler handler,Handler mHandler) {
		mContext = mc;
		this.tag = tag;
		if(tag!=null) {
			ms = ChocolateActivity.c_solver.getLatestMessages(this.tag);
//			ms.add(new Message(0, "haha", "http://www.baidu.com", "", "haha", 0, 0));
		}
		else {
			ms = new ArrayList<Message>();
			ms.clear();
		}
		myHandler = handler;
		moreHandler = mHandler;
	}
	@Override
	public Object getChild(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public long getChildId(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		return 0;
	}
	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		if(tag==null)
			return null;
		groupPosition--;
		LinearLayout ll;
		if(groupPosition == -1 || groupPosition == (ms.size()))
			return new LinearLayout(mContext);
		TextView tv;
		TextView tvmore;
		ll = new LinearLayout(mContext);
		tv = new TextView(mContext);
		tvmore = new TextView(mContext);
		AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		tv.setLayoutParams(layoutParams);
//		tvmore.setLayoutParams(layoutParams);
		ll.setOrientation(LinearLayout.VERTICAL);
		ll.addView(tv);
		ll.addView(tvmore);
		tv.setTextAppearance(mContext, R.style.TextAppearance_Medium);
		tvmore.setTextAppearance(mContext, R.style.TextAppearance_Medium);
		tv.setTextColor(0xff98f5ff);
//		tv.setTextColor(android.graphics.Color.BLACK);
//		if(childPosition==0)
		String temp = ms.get(groupPosition).summary;
		if(temp.equals("removeBBS Error!"))
			temp = "详情猛击更多！！";
			tv.setText(ToDBC(temp)+"\n"+ms.get(groupPosition).time);
//		else if(childPosition==1)
//			tv.setText(ms.get(groupPosition).time);
//		else if(childPosition==1){
//			tvmore.setLayoutParams(layoutParams);
			tvmore.setText("更多...");
			tvmore.setTextColor(android.graphics.Color.GREEN);
			//tv.setMovementMethod(LinkMovementMethod.getInstance());
			final int position = groupPosition;
			tvmore.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub  
					Uri content_url = Uri.parse(ms.get(position).link);   
					Intent intent = new Intent(Intent.ACTION_VIEW, content_url);  
					mContext.startActivity(intent); 
				}

			});
//		}
//		else;
		return ll;
	}
	@Override
	public int getChildrenCount(int groupPosition) {
		// TODO Auto-generated method stub
		if(groupPosition==0||groupPosition==(ms.size()+1))
			return 0;
		return childSize;
	}
	@Override
	public Object getGroup(int groupPosition) {
		// TODO Auto-generated method stub
		if(groupPosition==0||groupPosition==(ms.size()))
			return null;
		return ms.get(groupPosition);
	}
	@Override
	public int getGroupCount() {
		// TODO Auto-generated method stub
		if(tag==null)
			return 0;
		return ms.size()+2;
	}
	@Override
	public long getGroupId(int groupPosition) {
		// TODO Auto-generated method stub
		return 0;
	}
	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		if(tag==null)
			return null;
		groupPosition--;
		final LinearLayout ll = new LinearLayout(mContext);
		AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		if(groupPosition == -1){
			final TextView update = new TextView(mContext);
			layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, (80*screenWidth)/480);
			update.setLayoutParams(layoutParams);
			update.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
//			update.setTextColor(android.graphics.Color.WHITE);
//			update.setBackgroundColor(android.graphics.Color.BLACK);
			update.setTextAppearance(mContext, android.R.style.TextAppearance_Large);
//			update.setTextColor(0xff8b4513);
			if(!isFlush) {
				if(isMore)
					update.setEnabled(false);
				update.setText("更新");
/*				update.setOnTouchListener(new OnTouchListener(){

					@Override
					public boolean onTouch(View arg0, MotionEvent event) {
						// TODO Auto-generated method stub
						if(event.getAction() == MotionEvent.ACTION_UP){
//							update.setBackgroundColor(android.graphics.Color.BLACK);
						} 
						if(event.getAction() == MotionEvent.ACTION_DOWN){
//							update.setBackgroundColor(android.graphics.Color.YELLOW);
						}
						return false;
					}

				});*/

				update.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View v) {
						Log.d("update", "update once");
						ChocolateActivity.c_solver.requestLatestMessage(tag, myHandler);
						isFlush = true;
						myNotifyDataSetChanged();
						// TODO Auto-generated method stub

					}

				});
			}
			else {
				update.setText("获取数据中...");
//				ll.setBackgroundColor(android.graphics.Color.BLACK);
				ProgressBar wait = new ProgressBar(mContext);
				double anstemp = screenWidth*45d/480d;
				wait.setPadding(0, 0, 0, 0);
//				wait.
//				wait.setDrawingCacheBackgroundColor(0xff8b4513);
				ll.addView(wait);
				update.setEnabled(false);
			}
			
			ll.addView(update);
			return ll;
		}
		else if(groupPosition == (ms.size())) {
			final TextView update = new TextView(mContext);
			layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, (80*screenWidth)/480);
			update.setLayoutParams(layoutParams);
			update.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
//		update.setTextColor(android.graphics.Color.WHITE);
//			update.setBackgroundColor(android.graphics.Color.BLACK);
			update.setTextAppearance(mContext, android.R.style.TextAppearance_Large);
//			update.setTextColor(0xff8b4513);
			if(!isMore) {
				if(isFlush)
					update.setEnabled(false);
				update.setText("更多");
/*				update.setOnTouchListener(new OnTouchListener(){

					@Override
					public boolean onTouch(View arg0, MotionEvent event) {
						// TODO Auto-generated method stub
						if(event.getAction() == MotionEvent.ACTION_UP){
//							update.setBackgroundColor(android.graphics.Color.BLACK);
						} 
						if(event.getAction() == MotionEvent.ACTION_DOWN){
//							update.setBackgroundColor(android.graphics.Color.YELLOW);
						}
						return false;
					}

				});*/

				update.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View v) {
						Log.d("more", "more once");
						ChocolateActivity.c_solver.requestNextPage(tag, moreHandler);
						isMore = true;
						myNotifyDataSetChanged();
						// TODO Auto-generated method stub

					}

				});
			}
			else {
				update.setText("获取数据中...");
				ProgressBar wait = new ProgressBar(mContext);
				double anstemp = screenWidth*45d/480d;
				wait.setPadding(0, 0, 0, 0);
				wait.setDrawingCacheBackgroundColor(android.graphics.Color.GRAY);
				ll.addView(wait);
				update.setEnabled(false);
			}
			ll.addView(update);
			return ll;
		}
		TextView tv;
		tv = new TextView(mContext);
		tv.setTextAppearance(mContext, android.R.style.TextAppearance_Large);
		tv.setLayoutParams(layoutParams);
		// Center the text vertically
		tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
		// Set the text starting position
		double anstemp = screenWidth*20d/480d;
		tv.setPadding(0, 0, (int) (screenWidth*45d/480d), 0);
		tv.setText(ToDBC(ms.get(groupPosition).title));
		final TextView tv2 = new TextView(mContext);
//		tv2.setText("收藏");
		layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		tv2.setLayoutParams(layoutParams);
		tv2.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
		anstemp = screenWidth*45d/480d;
		tv2.setPadding(0, 0, 0, 0);
		tv2.setTextAppearance(mContext, android.R.style.TextAppearance_Large);
		tv2.setTextColor(android.graphics.Color.YELLOW);
		ll.addView(tv2);
		ll.addView(tv);
		if(ms.get(groupPosition).favorite!=0)
			tv2.setText("★");
		else tv2.setText("☆");
		final int position = groupPosition;
		tv2.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				//Modify BY JHT
				if(ms.get(position).favorite!=0) {
					tv2.setText("☆");
					//ms.get(position).favorite = 0;
					ChocolateActivity.c_solver.cancleCollectMessage(ms.get(position));
					Toast.makeText(mContext, "取消收藏", Toast.LENGTH_SHORT).show();
				}
				else {
					tv2.setText("★");
					//ms.get(position).favorite = 1;
					ChocolateActivity.c_solver.collectMessage(ms.get(position));
					Toast.makeText(mContext, "已收藏", Toast.LENGTH_SHORT).show();
				}
			}
			
		});
//		tv.setTextColor(0xff8b4513);
		if(ms.get(groupPosition).isRead==0)
			tv.getPaint().setFakeBoldText(true);
		else
			tv.getPaint().setFakeBoldText(false);
		tv2.getPaint().setFakeBoldText(true);
		return ll;
	}
	@Override
	public boolean hasStableIds() {
		// TODO Auto-generated method stub
		return true;
	}
	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		if(groupPosition==0||groupPosition==(ms.size()+1))
			return false;
		return true;
	}
	
	public void addMessage() {
		ArrayList<Message> tempMessages = ChocolateActivity.c_solver.getNextPage(tag);
		for(int i=0;i<tempMessages.size();i++)
			ms.add(tempMessages.get(i));
		isMore = false;
		isFlush = false;
		super.notifyDataSetChanged();
	}
	
	public void changeFlush() {
		isFlush = true;
		isMore = false;
		super.notifyDataSetChanged();
	}
	
	public void myNotifyDataSetChanged() {
		super.notifyDataSetChanged();
	}
	
	public void onGroupExpanded(int groupPosition) {
		groupPosition--;
		if(groupPosition>-1&&groupPosition<ms.size()) {
			ChocolateActivity.c_solver.setMessageRead(ms.get(groupPosition));
			ms.get(groupPosition).isRead=1;
		}
	}
	
	private String ToDBC(String input) {    
        char[] c = input.toCharArray();    
        for (int i = 0; i < c.length; i++) {    
            if (c[i] == 12288) {    
                c[i] = (char) 32;    
                continue;    
            }    
            if (c[i] > 65280 && c[i] < 65375)    
                c[i] = (char) (c[i] - 65248);    
        }    
        return new String(c);    
    }
}
